import asyncio
from config.static_var import TAG
from utils.api_connector import ApiConnector
from utils.common import extract_code_block


def _generate_prompt(cli_code: str) -> str:
    prompt = "## Requirement \n" 
    "Generate a Python script to execute the CLI commands provided in the previous step. "
    "example:\n\n"

    prompt += "```python\n" 
    with open("samples/sample_template.py.tpl", "r") as f:
        sample_template = f.read()
    prompt += sample_template
    prompt += "```\n\n"

    prompt += "Please complete following Python script as the example above. "

    prompt += "```python\n"
    with open("samples/main_function_template.py.tpl", "r") as f:
        sample_template = f.read()
        sample_template = sample_template.replace(TAG.CLI_CODE, cli_code)
    prompt += sample_template
    prompt += "```"

    prompt += """
## Output Format
1. The output must contain exactly one code block, enclosed within triple backticks (``` ```).
2. The code block must include only the completed `main` function, without any other content outside the `main` function.
. The code must be compatible with both Python 2.7 syntax and Python 3.x, including:
    - String formatting using `"{}".format()` instead of f-strings.
    - Avoiding type hints and other Python 3-specific features.
"""
    return prompt

def main(llm, cli_code: str, write_file: None | str = None, verbose: bool = False) -> str:
    """
    主函数，处理命令行参数并执行网络配置
    """
    # 生成提示信息
    prompt = _generate_prompt(cli_code)

    if verbose:
        print("Generated Prompt:")
        print(prompt)

    reply = llm.send_request(prompt)
    # from examples.lallmaIndex import send_request
    # reply = asyncio.run(send_request(prompt))
    
    if reply is None:
        raise ValueError("No reply received from the LLM.")
    if verbose:
        print("LLM Reply:")
        print(reply)
        print("Reasoning:")
    python_code = extract_code_block(reply)
    if verbose:
        print("Generated Python Script:")
        print(python_code)

    with open("samples/template.py.tpl", "r") as f:
        template = f.read()
        python_code = template.replace(TAG.MAIN_FUNCTION, python_code)
    
    if write_file:
        with open(write_file, "w") as f:
            f.write(python_code)
    
    return python_code
